package com.mall.car.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.address.entity.Address;
import com.mall.address.service.impl.AddressServiceImpl;
import com.mall.car.entity.Car;
import com.mall.car.service.impl.CarServiceImpl;
import com.mall.commondataformat.R;
import com.mall.dingdan.entity.Dingdan;
import com.mall.dingdan.service.impl.DingdanServiceImpl;
import com.mall.product.entity.Product;
import com.mall.user.entity.User;
import com.mall.user.service.impl.UserServiceImpl;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.mall.commonutils.ResultCode.USER_NOT_LOGIN;
import static com.mall.commonutils.SessionStaticMes.USER_IN_SESSION;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-11-03
 */
@RestController
@RequestMapping("/car")
public class CarController {

    @Autowired
    private CarServiceImpl carService;
    @Autowired
    private DingdanServiceImpl dingDanService;
    @Autowired
    private AddressServiceImpl addressService;
    @Autowired
    private UserServiceImpl userService;

    @ApiOperation("查询所有信息")
    @PostMapping("/carList")
    public R carList(HttpSession session) {
        User user = (User) session.getAttribute(USER_IN_SESSION);
        if (user == null) {
            return R.error().message(USER_NOT_LOGIN);
        }
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",user.getId());
        List<Car> list = carService.list(wrapper);
        return R.ok().data("tableData", list);
    }

    @ApiOperation("删除某一条购物车信息")
    @PostMapping("/deleteCarProduct")
    public R carDelete(Car car){
        if(car == null){
            return R.error().message("空信息");
        }
        if(carService.removeById(car.getId())){
            return R.ok();
        }
        else{
            return R.error().message("删除失败");
        }
    }

    @PostMapping("/addCarProduct")
    public R addCarProduct(Car car){
        if(car == null){
            return R.error().message("空信息");
        }
        Car productCar = new Car();
        productCar.setUserId(car.getUserId());
        productCar.setUserName(car.getUserName());
        productCar.setProductId(car.getProductId());
        productCar.setProductName(car.getProductName());
        productCar.setProductPicture(car.getProductPicture());
        productCar.setPrice(car.getPrice());
        productCar.setCount(car.getCount());
        productCar.setMoney(car.getMoney());
        if(carService.save(productCar)){
            return R.ok();
        }else{
            return R.error().message("加入失败");
        }
    }

    @ApiOperation("添加到购物车")
    @PostMapping("/addToCar")
    public R add(String product, String num, HttpSession session){
        User user = (User)session.getAttribute(USER_IN_SESSION);
        if(user == null){
            return R.error().message(USER_NOT_LOGIN);
        }
        JSONObject parse =(JSONObject)JSON.parse(product);
        Car car = new Car();
        car.setUserName(user.getUsername());
        car.setUserId(user.getId());
        car.setProductId(parse.getLong("id"));
        car.setProductName(parse.getString("name"));
        car.setProductPicture(parse.getString("picture"));
        car.setPrice(parse.getDouble("price"));
        car.setCount(Integer.valueOf(num));
        car.setMoney(parse.getDouble("price")*Integer.valueOf(num));

        if(!carService.save(car)){
            R.error().message("添加失败");
        }
        return R.ok();
    }

    @ApiOperation("支付")
    @PostMapping("/settle")
    public R settle(String tableData, int addressId, HttpSession httpSession){
        if(tableData == null) {
            return R.error().message("空信息");
        }
        User user=(User) httpSession.getAttribute(USER_IN_SESSION);
        if (user == null) {
            return R.error().message(USER_NOT_LOGIN);
        }
        List<JSONObject> data = new ArrayList();
        double totalMoney = 0;
        JSONArray objects = JSON.parseArray(tableData);
        for (Object object : objects) {
            JSONObject t = (JSONObject) object;
            data.add(t);
            totalMoney += Double.valueOf(t.get("money").toString());
//            QueryWrapper<Car> wrapper = new QueryWrapper<>();
//            wrapper.eq("id",id);
//            carDelete(carService.getOne(wrapper));
        }
        if (user.getMoney() < totalMoney){
            return R.error().message("钱不够！");
        }else{
            for (JSONObject object:data) {
                if(object.size() == 10 && object.get("choose").equals(true)) {
                    Dingdan dingdan = new Dingdan();
                    user.setMoney(user.getMoney() - Double.valueOf(object.get("money").toString()));
                    dingdan.setUserId(Long.valueOf(object.get("userId").toString()));

                    dingdan.setShangpinId(Long.valueOf(object.get("productId").toString()));

                    dingdan.setAccpetAddress(addressService.getById(addressId).getContent());

                    dingdan.setUsername(user.getUsername());

                    dingdan.setAcceptName(addressService.getById(addressId).getName());

                    dingdan.setProductName((String) object.get("productName"));

                    dingdan.setAcceptPhone(addressService.getById(addressId).getPhone());

                    dingdan.setIsPay(1);
                    dingdan.setIsAccept(0);
                    dingdan.setIsSend(0);

                    if (!dingDanService.save(dingdan)) {
                        return R.error().message("添加订单失败！");
                    }

                    QueryWrapper<Car> wrapper = new QueryWrapper<>();
                    wrapper.eq("id", object.get("id"));
                    carDelete(carService.getOne(wrapper));
                }
            }
            userService.saveOrUpdate(user);
        }
        return R.ok();
    }
}

